package com.zlyx.easy.log.reader;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ResourceUtils;

import com.zlyx.easy.core.annotations.SpringBean;
import com.zlyx.easy.core.event.LogEvent;
import com.zlyx.easy.core.tool.Ops;
import com.zlyx.easy.core.utils.LogUtils;
import com.zlyx.easy.core.utils.SpringUtils;
import com.zlyx.easy.log.config.LogProperties;

@SpringBean(todo = { "日志文件Reader" })
public class LogFileReader implements ApplicationContextAware {

	private long lastTimeFileSize = 0;

	@Autowired
	private LogProperties properties;

	@SuppressWarnings("resource")
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		String logPath = properties.getLogPath();
		try {
			if (Ops.isNotEmpty(logPath)) {
				File logFile = ResourceUtils.getFile(logPath);
				final RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
				// 指定文件可读可写
				ScheduledExecutorService exec = Executors.newScheduledThreadPool(2);
				exec.scheduleWithFixedDelay(new Runnable() {
					@Override
					public void run() {
						try {
							randomFile.seek(lastTimeFileSize);
							String tmp = "";
							while ((tmp = randomFile.readLine()) != null) {
								String log = new String(tmp.getBytes("ISO8859-1"));
								SpringUtils.publish(new LogEvent(log));
							}
							lastTimeFileSize = randomFile.length();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}, 0, 1, TimeUnit.SECONDS);
			}
		} catch (IOException e) {
			LogUtils.err(e);
		}
	}

	/**
	 * 监听日志文件
	 *
	 * @throws IOException
	 */
	@PostConstruct
	public void start() throws IOException {

	}
}